import { View, Text, hideMenuButton, navigateBack, ScrollView, Button } from '@ray-js/ray';
import React, { useRef, useState } from 'react';
import { NavBar, Icon, DialogInstance, Dialog } from '@ray-js/smart-ui';
import { getStatusBarHeight, rpx2pxNum, SegmentData, TimeGroup } from '@/utils';
import HeatTimeViewGroup from '@/components/HeatTimeView/HeatTimeViewGroup';
import iconArrow from '../../res/imgs/ic_back_white.png';
import Styles from './index.module.less';
import TimerTureSectorDialog from '@/components/TimerTureSectorDialog/TimerTureSectorDialog';
import TimerTimeSectorDialog from '@/components/TimerTimeSectorDialog/TimerTimeSectorDialog';
import BottomComfimView from '@/components/BottomComfimView';
import { useActions, useProps } from '@ray-js/panel-sdk';
import { useEffect } from 'react';
import Strings from '@/i18n';
export function HeatTimer() {
  const actions = useActions();
  const top = getStatusBarHeight() + rpx2pxNum(88);
  // 初始化解析数据存储数组
  const [parsedData, setParsedData] = useState<SegmentData[]>([]);
  const myHeatSet = useProps(props => props.Heat_Program);
  console.log('myHeatSet', myHeatSet);
  useEffect(() => {
    getDatas();
  }, [myHeatSet]);
  const mGroupRef = useRef(0);  // 用来存储点击的组
  const mChildRef = useRef(0);  // 用来存储点击的子组
  const selectTureCallBack = (value: number) => {//选择了温度选择器弹窗
    console.log('点击了温度选择器弹窗', value);
    setShowTurmDialog(false);
     // 确保 value 是数字类型
 
    if (value > 0) {//更新温度值
      updateTemperature(mGroupRef.current, mChildRef.current, value);
    }
  };

  // 新增：更新温度的函数
  const updateTemperature = (segmentIndex: number, groupIndex: number, newTemperature: number) => {
    setParsedData(prevData => {
      const newData = [...prevData];
      if (newData[segmentIndex] && newData[segmentIndex].groups[groupIndex]) {
        newData[segmentIndex].groups[groupIndex].temperature = newTemperature; //十进制的40
      }
      return newData;
    });
  };

  // 新增：更新开关状态的函数
  const updateSwitch = (segmentIndex: number, groupIndex: number, isOn: boolean) => {
    setParsedData(prevData => {
      const newData = [...prevData];
      if (newData[segmentIndex] && newData[segmentIndex].groups[groupIndex]) {
        // 检查结束时间是否大于开始时间
        const group = newData[segmentIndex].groups[groupIndex];
        if (group.endTime > group.startTime) {
          // 只有当结束时间大于开始时间时才更新开关状态
          // 根据规则：b0=1 代表 1 组选中...b3=1 代表 4 组选中
          // 需要操作第(7-groupIndex)位
          let selectionMarkBinary = parseInt(prevData[segmentIndex].selectionMark, 2);
          if (isOn) {
            // 设置对应位为1
            selectionMarkBinary |= (1 << groupIndex);
          } else {
            // 设置对应位为0
            selectionMarkBinary &= ~(1 << groupIndex);
          }
          newData[segmentIndex].selectionMark = selectionMarkBinary.toString(2).padStart(8, '0');
        } else {
          openTimeErrorDialog();
          console.log('结束时间必须大于开始时间，无法更新开关状态');
        }
      }
      return newData;
    });
  };

  /**
   * 
   * @param group 开关
   * @param child 
   * @param on 
   */
  const onSwitch = (group: number, child: number, on: boolean) => {
    console.log('onSwitch-回调', group, child, on);
    // 在这里调用更新开关的方法
    updateSwitch(group, child, on);
  }

  const onTimeListener = (start: number, end: number) => {//选择了温度选择器弹窗
    console.log('点击了时间段选择器弹窗', start, end);
    setShowTimeDialog(false);
    if (start < 0) {
      return;
    }
    if (end > start) {//更新时间段
      updateTimes(mGroupRef.current, mChildRef.current, start, end);
    } else {
      openTimeErrorDialog();
      console.log('onTimeListener', '结束时间需要大于开始时间');
    }
  };

  // 新增：更新时间段的函数
  const updateTimes = (segmentIndex: number, groupIndex: number, newStartTime: number, newEndTime: number) => {
    setParsedData(prevData => {
      const newData = [...prevData];
      if (newData[segmentIndex] && newData[segmentIndex].groups[groupIndex]) {
        newData[segmentIndex].groups[groupIndex].startTime = newStartTime;
        newData[segmentIndex].groups[groupIndex].endTime = newEndTime;
      }
      return newData;
    });
  };

  const clickWeekDayToggle = (group: number, week: number) => {//点击了星期选择器
    console.log('点击了星期选择器', 'group:' + group + ',week:' + week);
    updateWeekDay(group, week);
  };

  /**
   * 
   * @param segmentIndex 更新星期数据，只有能点击才会调用，所以不需要判断不能点击的情况
   * @param week 
   */
  const updateWeekDay = (segmentIndex: number, day: number) => {
    setParsedData((prevData) => {
      const newData = [...prevData];
      let weekDayBinary = parseInt(prevData[segmentIndex].weekDay, 2);//日期二进制
      let isSelected = parsedData[segmentIndex].weekDay.charAt(7 - day) === '1';//当前的是否已选中
      if (isSelected) {
        weekDayBinary &= ~(1 << day);  //对应的位置置为0，其他几端保持不变
        console.log('updateWeekDay-128', 'segmentIndex:' + segmentIndex + ',day:' + day + ',设置0');
      } else {
        weekDayBinary |= (1 << day);  //未选中，则置为1
        console.log('updateWeekDay-130', 'segmentIndex:' + segmentIndex + ',day:' + day + ',设置1');
      }
      newData[segmentIndex].weekDay = weekDayBinary.toString(2).padStart(8, '0');
      // 输出解析后的完整数据
      console.log('updateWeekDay-135:', weekDayBinary.toString(2) + ',' + weekDayBinary.toString(2).padStart(8, '0'));
      console.log('updateWeekDay-136:', newData);
      return newData;
    })
  }


  /**
   * 获取数据
   */
  function getDatas() {
    // 打印原始数据长度用于调试
    console.log('myHeatSet-字数长度', myHeatSet?.length);

    // 验证数据类型和长度是否符合预期的176字符长度
    if (typeof myHeatSet === 'string' && myHeatSet.length === 176) { // 修改条件判断为176字符

      // 输出有效数据提示
      console.log('myHeatSet-有效数据');

      // 定义数据结构参数
      const segmentLength = 22; // 每段22字节
      const totalSegments = 4;  // 总共4段
      const groupsPerSegment = 4; // 每段包含4组数据
      const newParsedData: SegmentData[] = [];

      // 遍历每个数据段
      for (let segmentIdx = 0; segmentIdx < totalSegments; segmentIdx++) {

        // 计算当前段在字符串中的起始位置（每个字节用2个十六进制字符表示）
        const segmentStart = segmentIdx * segmentLength * 2; //0x44 ,1x44,2x44,3x44(0,44,88,132)
        // console.log('segmentStart:' + segmentIdx, segmentStart);
        // 创建当前段的组数据数组
        const groups: TimeGroup[] = [];

        // 解析段内的每组数据
        for (let groupIdx = 0; groupIdx < groupsPerSegment; groupIdx++) {

          // 计算当前组在字符串中的起始位置
          const groupStart = segmentStart + groupIdx * 5 * 2; // 每组5字节，转为16进制字符串位置
          // console.log('groupStart:' + groupIdx, groupStart);
          // 提取并解析开启时间的十六进制字符串
          const startTimeHex = myHeatSet.slice(groupStart, groupStart + 4);
          const startTime = parseInt(startTimeHex, 16);

          // 提取并解析关闭时间
          const endTimeHex = myHeatSet.slice(groupStart + 4, groupStart + 8);
          const endTime = parseInt(endTimeHex, 16);

          // 提取并解析设定温度
          const tempHex = myHeatSet.slice(groupStart + 8, groupStart + 10);
          const temperature = parseInt(tempHex, 16);
          console.log(`温度数据读取转化: `, "tempHex:" + tempHex + ',temperature:' + temperature);
          // 将解析后的数据添加到组数组
          groups.push({
            startTime,
            endTime,
            temperature
          });
        }

        // 提取并解析组选中标记
        const selectionMarkHex = myHeatSet.slice(segmentStart + 40, segmentStart + 42);
        const selectionMark = parseInt(selectionMarkHex, 16).toString(2).padStart(8, '0');

        // 提取并解析适用星期
        const weekDayHex = myHeatSet.slice(segmentStart + 42, segmentStart + 44);
        const weekDay = parseInt(weekDayHex, 16).toString(2).padStart(8, '0');

        // 将段数据添加到结果数组
        newParsedData.push({
          groups,
          selectionMark,
          weekDay
        });
      }

      setParsedData(newParsedData);

      // 输出解析后的完整数据
      console.log('解析后的数据:', newParsedData);

      // 遍历并输出每段每组的详细信息
      newParsedData.forEach((segment, segmentIndex) => {

        // 输出段索引信息
        console.log(`段 ${segmentIndex + 1} 信息:`);

        // 以二进制形式输出适用星期
        console.log(`适用星期: ${segment.weekDay}`);

        // 以二进制形式输出组选中标记
        console.log(`组选中标记: ${segment.selectionMark}`);

        // 遍历并输出每组详细信息
        segment.groups.forEach((group, groupIndex) => {

          // 将分钟转换为小时:分钟格式
          const startHours = Math.floor(group.startTime / 60);
          const startMinutes = group.startTime % 60;
          const endHours = Math.floor(group.endTime / 60);
          const endMinutes = group.endTime % 60;

          // 输出具体信息
          console.log(`组 ${groupIndex + 1}:`);
          console.log(`  开启时间: ${startHours}小时${startMinutes}分钟`);
          console.log(`  关闭时间: ${endHours}小时${endMinutes}分钟`);
          console.log(`  设定温度: ${group.temperature}℃`);
        });
      });

    } else {
      // 数据不符合要求时输出错误信息
      console.error('myHeatSet 不是有效的 176 字节十六进制字符串');

    }

  }

  console.log('myHeatSet', myHeatSet);
  hideMenuButton();
  // 点击左边返回按钮
  const clikBack = () => {
    // navigateBack()
    openSaveDialog();

  };

  const openTimeErrorDialog = () => {
    DialogInstance.confirm({
      selector: '#dialog',
      title: Strings.getLang('m_tip'),
      message: Strings.getLang('m_msg_time_error'),
      confirmButtonText: Strings.getLang('m_confirm'),
      cancelButtonText: Strings.getLang('m_cancel'),
      customStyle: { backgroundColor: '#353535', color: '#353535' },
    })
      .then(() => {
        // 确认
      })
      .catch(() => {
        // 取消
      });
  };


  /**
   * 保存数据
   */
  /**
 * 保存数据 - 将parsedData转换为十六进制字符串
 */
  const saveData = (): string => {
    try {
      let result = '';
        console.log('saveData解析后的数据:', parsedData);
      // 确保有4段数据
      for (let segmentIdx = 0; segmentIdx < 4; segmentIdx++) {
        if (!parsedData[segmentIdx]) {
          console.error(`缺失第${segmentIdx + 1}段数据`);
          return '';
        }

        const segment = parsedData[segmentIdx];

        // 每段有4组时间数据
        for (let groupIdx = 0; groupIdx < 4; groupIdx++) {
          if (!segment.groups[groupIdx]) {
            console.error(`段${segmentIdx + 1}缺失第${groupIdx + 1}组数据`);
            return '';
          }

          const group = segment.groups[groupIdx];

          // 开始时间 (2字节) - 转换为4位十六进制
          const startTimeHex = group.startTime.toString(16).padStart(4, '0');

          // 结束时间 (2字节) - 转换为4位十六进制
          const endTimeHex = group.endTime.toString(16).padStart(4, '0');

          // 温度 (1字节) - 转换为2位十六进制
          const tempHex = group.temperature.toString(16).padStart(2, '0');
          // 拼接这5个字节的数据
          result += startTimeHex + endTimeHex + tempHex;
        }

        // 组选中标记 (1字节) - 转换为2位十六进制
        const selectionMarkDecimal = parseInt(segment.selectionMark, 2);
        const selectionMarkHex = selectionMarkDecimal.toString(16).padStart(2, '0');
        result += selectionMarkHex;

        // 适用星期 (1字节) - 转换为2位十六进制
        const weekDayDecimal = parseInt(segment.weekDay, 2);
        const weekDayHex = weekDayDecimal.toString(16).padStart(2, '0');
        result += weekDayHex;

      }
      console.log('原始的数据:', myHeatSet);
      console.log('保存的数据:', result);
      actions.Heat_Program.set(result);
      navigateBack();
      return result;
    } catch (error) {
      console.error('数据转换错误:', error);
      return '';
    }
  };

  const openSaveDialog = () => {
    DialogInstance.confirm({
      selector: '#dialog',
      title: Strings.getLang('m_tip'),
      message: Strings.getLang('m_msg_comfim_save'),
      confirmButtonText: Strings.getLang('m_confirm'),
      cancelButtonText: Strings.getLang('m_cancel'),
      customStyle: { backgroundColor: '#353535', color: '#353535' },
    })
      .then(() => {
        // 确认
        saveData()

      })
      .catch(() => {
        // 取消
        navigateBack()
      });
  };

  const [showTurmDialog, setShowTurmDialog] = useState(false);//是否显示温度选择器弹窗
  const [showTimeDialog, setShowTimeDialog] = useState(false);//是否显示时间选择器弹窗

  const clickTurmTurm = (group: number, child: number) => {//点击了温度选择器
    console.log('点击了温度选择器', 'group:' + group + ',child:' + child);
    mGroupRef.current = group;
    mChildRef.current = child;
    setShowTurmDialog(true);
  };

  const clickTimeSecltector = (group: number, child: number) => {//点击了温度选择器
    console.log('点击了时间选择器', 'group:' + group + ',child:' + child);
    mGroupRef.current = group;
    mChildRef.current = child;
    setShowTimeDialog(true);
  };

  return (
    <View className={Styles.app}>
      <View className={Styles.view}>
        <NavBar
          customClass={Styles.titlebar}
          leftArrow={false}
          safeAreaInsetTop // 是否留出安全距离
          fixed
          slot={{
            left: (
              <View
                style={{
                  width: '80px',
                  height: '40px',
                  display: 'flex',
                  flexDirection: 'row',
                  justifyContent: 'flex-start',
                }}
                onClick={clikBack}
              >
                <Icon name={iconArrow} size="20px" />
                <Text
                  style={{
                    color: 'white',
                    fontSize: '16px',
                    lineHeight: '40px',
                    textAlign: 'center',
                  }}
                >
                  {Strings.getLang('m_back')}
                </Text>
              </View>
            ),
          }}
        />

        <ScrollView
          refresherTriggered={false}
          refresherEnabled={false}
          scrollY
          style={{ top: `${top}px`, bottom: '125rpx' }}
          className={Styles.scrollView}
          id="scrollView"
        >
          <View className={Styles.topBackImg}>
            <Text
              style={{
                fontSize: '18px',
                color: 'white',
                width: '100%',
                height: '100%',
                textAlign: 'center',
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
              }}
            >
              {Strings.getLang('m_set_weekly_timer_for_heater')}
            </Text>
          </View>

          <HeatTimeViewGroup
            onSwitch={onSwitch}
            hasTemperature={true}
            clickTurmTurm={clickTurmTurm}
            clickWeekDayToggle={clickWeekDayToggle}
            clickTimeSecltector={clickTimeSecltector}
            data={parsedData}
          />
        </ScrollView>
      </View>
      <BottomComfimView onSave={() => { saveData() }} onCancle={() => { }} />
      <Dialog
        id="dialog"
        title='提示'
        message='请确认定时是否保存'
        customClass={Styles.dialog}
      />
      {showTimeDialog && <View style={{ display: 'flex', position: 'absolute', width: '100%', height: '100%', zIndex: 200 }}>
        <TimerTimeSectorDialog onTimeListener={onTimeListener}
          startTime={parsedData[mGroupRef.current].groups[mChildRef.current].startTime}
          endTime={parsedData[mGroupRef.current].groups[mChildRef.current].endTime} />
      </View>}
      {showTurmDialog && <View style={{ display: 'flex', position: 'absolute', width: '100%', height: '100%', zIndex: 200 }}>
        <TimerTureSectorDialog onClick={selectTureCallBack} value={parsedData[mGroupRef.current].groups[mChildRef.current].temperature} />
      </View>}
    </View>
  );
}

export default HeatTimer;
